/*
 * Copyright 2011 J. Auer, J. Andert, F.-J. Jendrusch, U. Celebi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.fuberlin.replication.storage.android.sqlite;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import de.fuberlin.replication.library.Subset;
import de.fuberlin.replication.library.Version;
import de.fuberlin.replication.storage.SubsetDAO;

/**
 * Android-specific SQLite {@link Subset} Data Access Object (DAO) implementation.
 */
public class SQLiteSubsetDAO extends SQLiteDAO implements SubsetDAO {
	/**
	 * @see SQLiteDAO#SQLiteDAO(SQLiteDatabaseHelper)
	 */
	public SQLiteSubsetDAO(SQLiteDatabaseHelper helper) {
		super(helper);
	}

	@Override
	public Iterable<Subset> getAll() {
		SQLiteDatabase db = getHelper().getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT s.id, k.replica, k.version "
				+ "FROM subset s LEFT JOIN knowledge k ON (s.id = k.subset_id);", null);

		return new SQLiteIterable<Subset>(new SQLiteSubsetIterator(cursor));
	}

	@Override
	public Subset create() {
		SQLiteDatabase db = getHelper().getWritableDatabase();

		long id = db.insert("subset", "id", null);

		Subset subset = new Subset();
		subset.setId(id);

		return subset;
	}

	@Override
	public void save(Subset subset) {
		SQLiteDatabase db = getHelper().getWritableDatabase();

		db.beginTransaction();

		try {
			// Unnecessary as long as replicas are not forgotten
			// db.delete("knowledge", "subset_id = ?", new String[] {String.valueOf(subset.getId())});

			for (Version version : subset.getKnowledge()) {
				ContentValues values = new ContentValues();
				values.put("subset_id", Long.valueOf(subset.getId()));
				values.put("replica", version.getReplica());
				values.put("version", Long.valueOf(version.getVersion()));

				db.insert("knowledge", null, values);
			}

			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}

	@Override
	public void delete(Subset subset) {
		SQLiteDatabase db = getHelper().getWritableDatabase();

		// Unnecessary as long as foreign key constraints are enforced (PRAGMA foreign_keys = ON)
		// db.delete("knowledge", "subset_id = ?", new String[] {String.valueOf(subset.getId())});

		db.delete("subset", "id = ?", new String[] {String.valueOf(subset.getId())});
	}
}